//
//  DataHandle.m
//  Days
//
//  Created by lanou3g on 16/1/7.
//  Copyright © 2016年 dss. All rights reserved.
//

#import "DataHandle.h"
#import "Model.h"
static DataHandle *_handle = nil;
@implementation DataHandle

+(instancetype)sharedDataHandle
{
    
    return [[self alloc]init];
    
    
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    
    static dispatch_once_t onecToken;
    dispatch_once(&onecToken, ^{
        if (_handle == nil) {
            _handle = [super allocWithZone:zone];
        }
    });
    return _handle;
    
}

-(void)getDataFromNet:(BLOCK)finishBlock
{

    NSString *string = @"http://japi.juhe.cn/joke/content/list.from?key=e61536321c9e0344c7d2ff974a19cb9f&page=1&pagesize=50&sort=asc&time=1418745237";
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        @autoreleasepool {
            if (data == nil || error != nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    finishBlock(nil);
                    return;
                });
            }
            //解析数据
            NSDictionary *Dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",Dict);
            NSDictionary *resultDict = Dict[@"result"];
            NSArray *array = resultDict[@"data"];
            
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in array) {
                Model *model = [[Model alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [arr addObject:model];
            }
            self.DataArray = [NSArray arrayWithArray:arr];
//            NSLog(@"*******%@",self.DataArray);
            //回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                finishBlock(self.DataArray);
            });
        }
    }];
    
    [task resume];


}




@end
